#include "chartdialog.h"
#include "ui_chartdialog.h"

ChartDialog::ChartDialog(SensorType type,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ChartDialog)
{
    ui->setupUi(this);

    // 绘制折线图相关参数
    lastPointKey = 0;
    lastFpsKey = 0;
    frameCount = 0;
    timeStart = QTime::currentTime();

    this->type = type;
    timer = new QTimer(this);
    initialWidgets();
    initialType(type);
    setupRealtimeData(ui->customPlot);

    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(btnClickedSlot()));
}

ChartDialog::~ChartDialog()
{
    if(timer->isActive())
        timer->stop();
    delete ui;
}

void ChartDialog::initialType(SensorType type)
{
    switch (type) {
    case LED:
        setWindowTitle("LED");
        ui->label_unit->setText("开/关");
        break;
    case BUZZER:
        setWindowTitle("蜂鸣器");
        ui->label_unit->setText("开/关");
        break;
    case VOLTAGE:
        setWindowTitle("电压");
        ui->label_unit->setText("V");
        break;
    case TEMPERATURE:
        setWindowTitle("温度");
        ui->label_unit->setText("℃");
        break;
    case HUMIDITY:
        setWindowTitle("湿度");
        ui->label_unit->setText("%");
        break;
    case PRESSURE:
        setWindowTitle("大气压");
        ui->label_unit->setText("hPa");
        break;
    case HEIGHT:
        setWindowTitle("海拔");
        ui->label_unit->setText("米");
        break;
    case LIGHT:
        setWindowTitle("光线");
        ui->label_unit->setText("lux");
        break;
    case X:
        setWindowTitle("陀螺仪-X轴");
        ui->label_unit->setText("μT");
        break;
    case Y:
        setWindowTitle("陀螺仪-Y轴");
        ui->label_unit->setText("μT");
        break;
    case Z:
        setWindowTitle("陀螺仪-Z轴");
        ui->label_unit->setText("μT");
        break;
    case COMPASS:
        setWindowTitle("电子罗盘");
        ui->label_unit->setText("μT");
        break;
    }
}

void ChartDialog::initialWidgets()
{
    ui->pushButton->setStyleSheet(QPushButton_STYTLE);
    ui->pushButton->resize(200,100);

    ui->dateTimeEdit_start->setDateTime(QDateTime::currentDateTime());
    ui->dateTimeEdit_end->setDateTime(QDateTime::currentDateTime());

    dialog = new QProgressDialog(this);
    dialog->setWindowTitle("历史数据导出");
    dialog->setWindowModality(Qt::WindowModal);
}


void ChartDialog::setupRealtimeData(QCustomPlot *customPlot)
{
    customPlot->addGraph(); // blue line
    QPen pen(QColor(40, 110, 255));
    pen.setWidth(4);
    customPlot->graph(0)->setPen(pen);

    QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
    timeTicker->setTimeFormat("%h:%m:%s");
    customPlot->xAxis->setTicker(timeTicker);
    customPlot->axisRect()->setupFullAxesBox();

    switch (type) {
    case LED:
        customPlot->yAxis->setRange(-0.3, 1.3);
        break;
    case BUZZER:
        customPlot->yAxis->setRange(-0.3, 1.3);
        break;
    case VOLTAGE:
        customPlot->yAxis->setRange(0, 5);
        break;
    case TEMPERATURE:
        customPlot->yAxis->setRange(-10, 40);
        break;
    case HUMIDITY:
        customPlot->yAxis->setRange(0, 150);
        break;
    case PRESSURE:
        customPlot->yAxis->setRange(300, 1100);
        break;
    case HEIGHT:
        customPlot->yAxis->setRange(0, 200);
        break;
    case LIGHT:
        customPlot->yAxis->setRange(0, 3000);
        break;
    case X:
        customPlot->yAxis->setRange(-800, 800);
        break;
    case Y:
        customPlot->yAxis->setRange(-800, 800);
        break;
    case Z:
        customPlot->yAxis->setRange(-800, 800);
        break;
    case COMPASS:
        // 待定
        customPlot->yAxis->setRange(-800, 800);
        break;
    }

    // make left and bottom axes transfer their ranges to right and top axes:
    connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
    connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

    // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
    connect(timer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
    timer->start(1000); // Interval 0 means to refresh as fast as possible
}

void ChartDialog::realtimeDataSlot()
{
    // calculate two new data points:
    double key = timeStart.msecsTo(QTime::currentTime())/1000.0; // time elapsed since start of demo, in seconds
    if (key-lastPointKey > 0.002) // at most add point every 2 ms
    {
        // TODO 添加坐标点
        switch (type) {
        case TEMPERATURE:
            ui->customPlot->graph(0)->addData(key, currentNode[0].fval);
            break;
        case HUMIDITY:
            ui->customPlot->graph(0)->addData(key, currentNode[1].fval);
            break;
        case LIGHT:
            ui->customPlot->graph(0)->addData(key, currentNode[2].ival);
            break;
        case PRESSURE:
            ui->customPlot->graph(0)->addData(key, currentNode[3].ival);
            break;
        case HEIGHT:
            ui->customPlot->graph(0)->addData(key, currentNode[4].ival);
            break;
        case VOLTAGE:
            ui->customPlot->graph(0)->addData(key, currentNode[5].fval);
            break;
        case X:
            ui->customPlot->graph(0)->addData(key, currentNode[6].fval);
            break;
        case Y:
            ui->customPlot->graph(0)->addData(key, currentNode[7].fval);
            break;
        case Z:
            ui->customPlot->graph(0)->addData(key, currentNode[8].fval);
            break;
        case COMPASS:
            // 待定
            ui->customPlot->graph(0)->addData(key, currentNode[9].fval);
            break;
        case LED:
            ui->customPlot->graph(0)->addData(key, currentNode[10].ival);
            break;
        case BUZZER:
            ui->customPlot->graph(0)->addData(key, currentNode[11].ival);
            break;
        }
        lastPointKey = key;
        // make key axis range scroll with the data (at a constant range size of 10):
        ui->customPlot->xAxis->setRange(key, 10, Qt::AlignRight);
        ui->customPlot->replot();

        // calculate frames per second:
        ++frameCount;
        if (key-lastFpsKey > 2) // average fps over 2 seconds
        {
            lastFpsKey = key;
            frameCount = 0;
        }
    }
}

void ChartDialog::btnClickedSlot()
{
    qint64 end = ui->dateTimeEdit_end->dateTime().toMSecsSinceEpoch()/1000;
    qint64 start = ui->dateTimeEdit_start->dateTime().toMSecsSinceEpoch()/1000;
    if((end-start)<=0)
    {
        QMessageBox::information(this,"提示","请输入有效的日期和时间区间！");
        return;
    }
    QString path = QFileDialog::getSaveFileName(this,"导出","","文本文档(*.txt)");
    if(path == "")
    {
        QMessageBox::warning(this,"提示","请选择输出路径！");
        return;
    }
    ExportDataThread* thread = new ExportDataThread(type,start,end,path,this);
    connect(thread,SIGNAL(progressSignal(int)),this,SLOT(progressSlot(int)));
    thread->start();

    dialog->setLabelText("历史数据导出中，请等待，导出过程请不要关闭此窗口。");
    dialog->setCancelButtonText("停止导出");

    dialog->show();
}

void ChartDialog::progressSlot(int value)
{
    dialog->setValue(value);
    if(value==100)
    {
        dialog->setLabelText("导出完成！");
        dialog->setCancelButtonText("停止导出");
    }
}

